package com.gl.basis.zuul.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.gl.basis.common.pojo.Page;
import com.gl.basis.zuul.config.RouteLocator;
import com.gl.basis.zuul.config.ZuulConfig;
import com.gl.basis.zuul.outdto.Route;
import com.gl.basis.zuul.service.ISysRouteService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * 路由管理
 *
 */
@RequestMapping("/route")
@RestController
public class RouteController implements InitializingBean {
	private static final Logger logger = LoggerFactory.getLogger(RouteController.class);

	@Autowired
	private RouteLocator routeLocator;

	@Autowired
	private ZuulConfig zuulConfig;

	@Autowired
	private ISysRouteService sysRouteService;

	/**
	 * 刷新路由信息
	 *
	 * @return 刷新结果
	 */
	@GetMapping("/refreshRoute")
	public Page<List<Route>> refresh() {
		List<Route> list = sysRouteService.get();
		routeLocator.setDirty(true, list);
		routeLocator.refresh();
		Page<List<Route>> page = new Page<List<Route>>();
		page.setResult(list);
		return page;
	}

	/**
	 * 查看当前路由信息
	 *
	 * @return 信息
	 */
	@RequestMapping("/watchRoute")
	public Page<?> watchNowRoute() {
		Map<String, Object> map = new HashMap<>();
		map.put("routes", routeLocator.getRoutes());
		map.put("blackList", zuulConfig.getBlackListAll());
		map.put("whiteList", zuulConfig.getWhiteListAll());
		Page<List<Route>> page = new Page<List<Route>>();
		page.setResult(map);
		return page;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		try {
			refresh();
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
		}
	}
}
